const { DefinePlugin, ProgressPlugin } = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

/**
 * @type {import('webpack').Configuration}
 */
const commonConfig = {
    entry: {
        app: './src/main.js',
    },    
    module: {
        rules: [
            {
                enforce: 'pre',
                test: /\.(js|vue)$/,
                loader: 'eslint-loader',
                exclude: /node_modules/
            },
            {
                test: /\.vue$/,
                use: 'vue-loader',
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                ]
            },
            {
                test: /\.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.(png|jpe?g|gif|webp)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    esModule:false, // 加载图片时路径 [object%20Module]
                    limit: 8196,
                    fallback: {
                        loader: 'file-loader',
                        options: {
                            name: () => process.env.NODE_ENV === 'production' ? 'img/[name].[hash:8].[ext]' : 'img/[name].[ext]',
                        }
                    }
                }
            }
        ]
    },
    
    optimization: {
        splitChunks: {
            cacheGroups: {
                vendors: {
                  name: `vendors`,
                  test: /[\\/]node_modules[\\/]/,
                  priority: -10,
                  chunks: 'initial'
                },
                common: {
                  name: `common`,
                  minChunks: 2,
                  priority: -20,
                  chunks: 'initial',
                  reuseExistingChunk: true
                }
            }
            // chunks: 'all'
        },
    },

    plugins: [
        new ProgressPlugin(),
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            template: 'public/index.html',
            minify: {
                collapseWhitespace: true //压缩为一行
            }
        }),

        new MiniCssExtractPlugin({
            filename:  () => process.env.NODE_ENV === 'production' ? 'css/[name].[contentHash:8].css': 'css/[name].css',
        }),

        new DefinePlugin({
            'BASE_URL': JSON.stringify('')
        })
    ]
}

module.exports = commonConfig